<?php

namespace App\Http\Traits\Auth;

use App\Events\Auth\Registered;
use App\Http\Requests\Auth\RegisterRequest;
use App\Models\AbstractUser;
use App\Models\Admin;
use App\Models\Business;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

trait RegisterTrait
{

    /**
     * 注册
     *
     * @param RegisterRequest $request
     *
     * @return AbstractUser|Admin|Business|User|\Illuminate\Database\Eloquent\Model
     */
    protected function register(RegisterRequest $request)
    {

        $data = $this->registerData($request);

        // 密码加密
        $data['password'] = Hash::make($request->input('password'));

        // 创建账号
        $user = $this->create($request, $data);

        $this->fireRegisteredEvent($user, $request);

        $this->registered($user);

        return $user;
    }

    /**
     * 返回注册数据
     *
     * @param Request $request
     *
     * @return array
     */
    protected function registerData(Request $request)
    {
        return $request->only(['mobile', 'name']);
    }

    /**
     * 创建账号
     *
     * @param Request $request
     * @param array $data
     *
     * @return AbstractUser|User|Admin|Business|\Illuminate\Database\Eloquent\Model
     */
    protected function create(Request $request, array $data)
    {
        return User::create($data);
    }

    /**
     * 注册完成
     *
     * @param AbstractUser $user
     */
    protected function registered(AbstractUser $user)
    {
        //
    }

    /**
     * 注册失败
     *
     * @param \Exception $exception
     */
    protected function registerFailed(\Exception $exception)
    {
        //
    }

    /**
     * 触发注册事件
     *
     * @param AbstractUser $user
     * @param Request $request
     */
    protected function fireRegisteredEvent(AbstractUser $user, Request $request)
    {
        event(new Registered($user, $request->ip()));
    }
}
